import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { gql, useQuery } from '@apollo/client';

import Button from '@kuiper-components/button';
import Table from '@kuiper-components/page-table';
import Select, { Option } from '@kuiper-components/select';

import HostSearchInput from '../../../../components/HostSearchInput';
import CopyBoard from '../../../../components/CopyBoard';

import { datetime } from '../../../../../common/formatter';
import {
  CHECK_CHANGE_TYPE,
  WARN_LEVEL_MAP,
	WARN_LEVEL_COLOR_MAP,
} from '../../../../../common/constants';
import s from './DetailTable.module.css';
import Box from '../Box';


export default function DetailTable({ className, taskId, stats }) {
	const [filter, setFilter] = React.useState({});
	const [tableData, setTableData] = React.useState([]);
	const [allData, setAllData] = React.useState([]);
	const handleFilterChange = custom => {
		setFilter({ ...filter, ...custom });
	};
	React.useEffect(() => {
		if (!Object.values(filter).some(e => e)) {
			init();
			return;
		}
		const tableData_ = allData?.reduce((arr, x) => {
			if (
				filter.affects &&
				x.affects.toLowerCase().indexOf(filter.affects.toLowerCase()) < 0
			) {
				return arr;
			}
			if (filter.level && String(x.level) !== String(filter.level)) {
				return arr;
			}
      if(filter.changeType && x.changeType.indexOf(filter.changeType) === -1){
        return arr;
      }
			arr.push({
				...x,
				endTime,
			});
			return arr;
		}, []);
		setTableData(tableData_);
	}, [filter]);
	const data = stats;
	const columns = [
		{
			key: 'endTime',
			title: '时间',
			dataIndex: 'endTime',
			render: x => datetime(x),
		},
		{
			key: 'affects',
			title: '风险地址',
			dataIndex: 'affects',
			render(affects) {
				return <CopyBoard className={s.target} text={affects} />;
			},
		},
    {
			key: 'changeType',
			title: '变更类型',
			dataIndex: 'changeType',
      render(changeType) {
				return <CopyBoard className={s.target} text={changeType.join(",")} />;
			},
		},
    {
			key: 'level',
			title: '威胁等级',
			dataIndex: 'level',
      render(level) {
        let color = WARN_LEVEL_COLOR_MAP[level].color
        let label = WARN_LEVEL_MAP[level]
				return <span style={{color}}>{label}</span>;
			},
		},
	];
	const endTime = data[0]?.endTime;

  const getChangeType = (warning)=>{
    let result = []
    if(warning.detail?.text) result.push("文本变更")
    if(warning.detail?.structure)  result.push("结构变更")
    if(warning.detail?.resource)  result.push("资源变更")
    return result
  }

	const init = () => {
		const tableData_ = stats.reduce((arr, task) => {
			const warnings = task?.result?.warnings || [];
			warnings.forEach(w => {
				arr.push({
					endTime: task?.endTime,
					affects: w?.affects,
					title: w?.title,
					level: w.level,
					isResolved: w.isResolved,
					ignoredTime: w.ignoredTime,
					id: w?._id,
          changeType: getChangeType(w)
				});
			});
			return arr;
		}, []);
		setAllData(tableData_);
		setTableData(tableData_);
	};
	React.useMemo(() => {
		init();
	}, [stats]);
	return (
		<Box
			title="篡改详情"
			className={cn(className, s.trend)}
			headerClass={s.header}
		>
			<div>
				<div className={s.toolbox}>
					<HostSearchInput
						placeholder="请输入风险地址"
						type="search"
						className={s.input}
						value={filter.affects}
						onChange={affects => handleFilterChange({ affects })}
					/>
					<div className={s.selectContainer}>
						<Select
							placeholder="请选择变更类型"
							onChange={changeType => handleFilterChange({ changeType })}
							className={s.select}
							allowClear
							value={filter?.changeType}
						>
							{Object.entries(CHECK_CHANGE_TYPE).map(
								([key, label]) =>	<Option key={key} value={label}>{label}</Option>
							)}
						</Select>
            <Select
							placeholder="请选择威胁等级"
							onChange={level => handleFilterChange({ level })}
							className={s.select}
							allowClear
							value={filter?.level}
						>
							{Object.entries({2: '低危', 4: '高危'}).map(
								([key, label]) =>	<Option key={key} value={key}>{label}</Option>
							)}
						</Select>
						<Button
							onClick={() =>
								handleFilterChange({
									category: undefined,
									status: undefined,
									level: undefined,
									affects: undefined,
                  changeType:undefined
								})
							}
						>
							重置
						</Button>
					</div>
				</div>
				<Table
					className={cn(s.table, 'tableFormat')}
					type="local"
					columns={columns}
					data={tableData}
				/>
			</div>
		</Box>
	);
}

DetailTable.propTypes = {
	className: PropTypes.string,
	taskId: PropTypes.string,
};

DetailTable.defaultProps = {
	className: s.detailTable,
};
